package com.mymoney.persistence.managers;

import java.util.List;

import javax.persistence.Query;

import com.mymoney.beans.LocationBean;
import com.mymoney.exceptions.MyMoneyException;
import com.mymoney.persistence.PersistenceContext;


public class LocationManager extends AbstractBeanManager<LocationBean> {


	public LocationManager(PersistenceContext persistenceContext) {
		super(persistenceContext);
	}
	
	
	@Override
	public void add(LocationBean location) {

		if(location != null)
		{
			storeEntity(location);
		}
	}

	
	public LocationBean getByCoordinates(Integer degrees, Integer minutes, Integer seconds) {

		LocationBean location = null;
		Query query = getEntityManager().createQuery("select p from LocationBean p where p.degrees = :degrees and p.minutes = :minutes and p.seconds = :seconds");
		query.setParameter("degrees", degrees);
		query.setParameter("minutes", minutes);
		query.setParameter("seconds", seconds);
		try
		{
			location = (LocationBean) query.getSingleResult();
		}catch (Exception e) {
			if(location == null)
			{
				if(degrees != null && minutes != null &&  seconds != null)
				{
					LocationBean newLocation = new LocationBean();
					newLocation.setDegrees(degrees);
					newLocation.setMinutes(minutes);
					newLocation.setSeconds(seconds);
					add(newLocation);
					location = newLocation;
				}
			}
		}
		return location;
	}


	@Override
	public List<LocationBean> list() throws MyMoneyException {
		
		String queryString = "select d from LocationBean d";
		List<LocationBean> locations = findAllEntities(queryString, -1,(Object[]) null);
		return locations;
	}


	@Override
	public LocationBean getByCode(long code) throws MyMoneyException {
		throw new MyMoneyException("Method is not implemented!");
	}


	@Override
	public LocationBean getById(Integer id) throws MyMoneyException {
		
		return getBy("select p from LocationBean p where p.id = :id", id, "id");
	}


	@Override
	public LocationBean getByName(String name) throws MyMoneyException {
		throw new MyMoneyException("Method is not implemented!");
	}


	@Override
	public void update(LocationBean first, LocationBean second)
			throws MyMoneyException {
		throw new MyMoneyException("Method is not implemented!");
		
	}


	@Override
	public void update(LocationBean entity, long code) throws MyMoneyException {
		throw new MyMoneyException("Method is not implemented!");
		
	}


	@Override
	public void update(LocationBean entity, Integer id) throws MyMoneyException {
		throw new MyMoneyException("Method is not implemented!");
		
	}


	@Override
	public void update(LocationBean entity, String name)
			throws MyMoneyException {
		throw new MyMoneyException("Method is not implemented!");
		
	}

}
